package com.maggroup.conference_system.common;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

import com.hankcs.hanlp.corpus.dictionary.item.Item;

/**
 * 分页查询实体
 * @author peng
 *
 */
public class PageInfo implements Pageable,Serializable{

	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3233398020402617765L;

	public static final int DEFAULT_PAGE_SIZE = 10;
	
	private int pageNumber;
	
	private int pageSize = DEFAULT_PAGE_SIZE;
	
	private Sort sort;
	
	private Map<String, Object> sortMap;
	
	public PageInfo() {
	}
	
	public PageInfo(int pageNumber,int pageSize) {
		if(pageNumber<0) {
			throw new IllegalArgumentException("page index must be not less than zero!");
		}
		if(pageSize<1) {
			throw new IllegalArgumentException("page size must be not less than one!");
		}
		this.pageNumber = pageNumber;
		this.pageSize = pageSize;
	}

	public PageInfo(int pageNumber,int pageSize,Sort sort) {
		this(pageNumber, pageSize);
		this.sort = sort;
	}
	
	
	
	public int getPageNumber() {
		return pageNumber;
	}

	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public Sort getSort() {
		return sort;
	}

	public void setSort(Sort sort) {
		this.sort = sort;
		
	}

	public Map<String, Object> getSortMap() {
		return sortMap;
	}

	public void setSortMap(Map<String, Object> sortMap) {
		this.sortMap = sortMap;
		List<Order> sorts = new ArrayList<>();
		sortMap.forEach((k,v)->{
			if(v.equals("asc")) {
				sorts.add(Order.asc(k));
			}else {
				sorts.add(Order.desc(k));
			}
		});
		this.sort = new Sort(sorts);
//		Iterator<String> iterator = sortMap.keySet().iterator();
//		List<String> keys = new ArrayList<String>();
//		while(iterator.hasNext()) {
//			keys.add(iterator.next());
//		}
//		
//		if(sort == null && keys.size()>0)
//			this.sort = new Sort(Direction.DESC, keys);
	}

	@Override
	public long getOffset() {
		return pageNumber*pageSize;
	}

	@Override
	public Pageable next() {
		return new PageInfo(pageNumber+1, pageSize,sort);
	}
	
	public Pageable previous() {
		return getPageNumber()==0?this:new PageInfo(getPageNumber()-1, getPageSize(), getSort());
	}

	@Override
	public Pageable previousOrFirst() {
		return hasPrevious()?previous():first();
	}

	@Override
	public Pageable first() {
		return new PageInfo(0,pageSize,sort);
	}

	@Override
	public boolean hasPrevious() {
		return pageNumber>0;
	}
	
}
